package nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

public class GroupChatClient {
    private static final String SERVER_HOST = "127.0.0.1";
    private static final int SERVER_PORT = 9999;
    private static Selector selector;
    private static SocketChannel channel;

    public GroupChatClient() {
        // 进行初始化
        try {
            selector = Selector.open();
            channel = SocketChannel.open();
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_READ);
            if (!channel.connect(new InetSocketAddress(SERVER_HOST, SERVER_PORT))) {
                while (!channel.finishConnect()) {
                    System.out.println("等待连接...");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送消息
     * @param msg
     */
    public void sendMsg(String msg) {
        try {
            msg = channel.getLocalAddress() + " 发送消息: " + msg;
            ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
            int write = channel.write(byteBuffer);
            if (write > 0) {
                System.out.println("发送成功");
            } else {
                System.out.println("发送失败...");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void receiveMsg() throws IOException {
        while (true) {
            int select = selector.select();
            if (select > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    SocketChannel socketChannel = (SocketChannel)key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int read = socketChannel.read(buffer);
                    if (read > 0) {
                        System.out.println(new String(buffer.array(), 0, read));
                    }
                }
            }
        }
    }
    public static void main(String[] args) {
        GroupChatClient client = new GroupChatClient();
        Scanner scanner = new Scanner(System.in);
        new Thread(() -> {
            try {
                client.receiveMsg();
                Thread.sleep(1000);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
        while (true) {
            String msg = scanner.nextLine();
            client.sendMsg(msg);
        }
    }
}
